package net.hzlj.platform.enterprise.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;

import net.hzlj.platform.enterprise.BootApp;
import net.hzlj.platform.enterprise.beans.ui.LocationBean;
import net.hzlj.platform.enterprise.common.Constant;
import net.hzlj.platform.enterprise.helper.RealTimeLocationManager;
import net.hzlj.platform.enterprise.helper.ToastHelper;
import net.hzlj.platform.enterprise.socket.Command;
import net.hzlj.platform.enterprise.socket.SocketManager;
import net.hzlj.platform.enterprise.socket.mina.MinaClientManager;
import net.hzlj.platform.enterprise.utils.AppPreferencesUtils;
import net.hzlj.platform.enterprise.utils.DateUtils;
import net.hzlj.platform.enterprise.utils.PreferencesUtils;
import net.hzlj.platform.enterprise.utils.StringUtils;

/***
 * @Description: Socket 接收数据处理
 * @Author: Jason Zhang
 * @Date: 2017/06/28
 */
public class SocketReceiver extends BroadcastReceiver {

    public static final String TAG = SocketReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null) {
            String action = intent.getAction();
            Log.i(TAG, "Date:" + DateUtils.convertDateLongToString(System.currentTimeMillis(), DateUtils.DATE_YMD_HMS) + ",action:" + action);
            if (Constant.Intent.ACTION_SOCKET_START.equals(action)) {
                if (BootApp.isConnect() && BootApp.getInstance().isLogin() && !SocketManager.getInstance().isConnection()) {
                    SocketManager.getInstance().reconnect();
                }
                if (!RealTimeLocationManager.getInstance().isRunning()) {
                    RealTimeLocationManager.getInstance().startLocation();
                }
            } else if (Constant.Intent.ACTION_SOCKET_DESTORY.equals(action)) {
                SocketManager.getInstance().close();
                RealTimeLocationManager.getInstance().destroy();
            } else if (Constant.Intent.ACTION_SOCKET_RECONNECT.equals(action)) {
                if (BootApp.isConnect() && BootApp.getInstance().isLogin() && !SocketManager.getInstance().isConnection()) {
                    SocketManager.getInstance().reconnect();
                }
                if (!RealTimeLocationManager.getInstance().isRunning()) {
                    RealTimeLocationManager.getInstance().startLocation();
                }
            } else if (Constant.Intent.ACTION_SOCKET_CLOSE.equals(action)) {
                SocketManager.getInstance().close();
            } else if (Constant.Intent.ACTION_SOCKET_MESSAGE_SEND.equals(action)) {
                String message = (String) intent.getSerializableExtra("Message");
                Log.i(TAG, "Send Message:" + message);
                if (!RealTimeLocationManager.getInstance().isRunning()) {
                    RealTimeLocationManager.getInstance().startLocation();
                }
                if (BootApp.isConnect() && BootApp.getInstance().isLogin() && StringUtils.isNotEmpty(message)) {
                    SocketManager.getInstance().sendMessage(message);
                }
            } else if (Constant.Intent.ACTION_SOCKET_MESSAGE_RECEIVED.equals(action)) {
                //Socket 接收内容
                String message = (String) intent.getSerializableExtra("Message");
                Log.i(TAG, "Receive Message:" + message);

                if (Constant.Socket.CONNECTION_TYPE == Constant.Socket.TYPE.NETTY) {
                    //Json 解析
                    if (StringUtils.isNotEmpty(message)) {
                        try {
                            Log.i(TAG, "Receive success Message:" + message);
                            LocationBean locationBean = new LocationBean();
                            LocationBean command = new Gson().fromJson(message, LocationBean.class);
                            Log.i(TAG, command.toString());
                            if (command.getType() == 1) {
                                command.setId(BootApp.getInstance().getUserTelephone());
                                /***
                                 * 发送指令接口
                                 * 回执内容需要与服务器协商，现需要处理的功能：
                                 * 1.实时定位一次(实时上报一次位置信息) --- (command="reportOnceLocation",type=1)
                                 * 2.实时定位（定位间隔为1s）--- (command="realTimeLocation",type=1)
                                 * 3.设置定位间隔（分钟）--- (command="setTimeInterval=60",type=1)
                                 * 4.卸载APP --- (command="uninstallApp",type=1)
                                 * 5.退出登录 --- (command="exitLogin",type=1)
                                 */
                                if (StringUtils.isNotEmpty(command.getMessage())) {
                                    if (command.getMessage().contains("reportOnceLocation")) {
                                        RealTimeLocationManager.getInstance().reportOnceLocation(command);
                                    } else if (command.getMessage().contains("setTimeInterval")) {
                                        String intervalStr = command.getMessage().replaceAll("setTimeInterval@", "");
                                        int interval = StringUtils.toInt(intervalStr);//分钟
                                        if (interval > 0) {
                                            //保存秒
                                            AppPreferencesUtils.putInt(context, PreferencesUtils.KEY_LOCATION_INTERVAL, interval * 60);
                                            RealTimeLocationManager.getInstance().updateLocationTime();
                                            SocketManager.getInstance().sendMessage(new Gson().toJson(command));
                                        }
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.e(TAG, "格式化指令错误", e);
                        }
                    }
                } else if (Constant.Socket.CONNECTION_TYPE == Constant.Socket.TYPE.NINA) {
                    /*if (!TextUtils.isEmpty(message) && message.contains("ti")) {
                        String intervalStr = "";
                        String[] b = message.split(",");
                        for (int i = 0; i < b.length; i++) {
                            if (b[i].contains("ti")) {
                                intervalStr = b[i];
                                break;
                            }
                        }
                        intervalStr = intervalStr.substring(intervalStr.indexOf('=') + 1);
                        int interval = 0;
                        if (StringUtils.isNumeric(intervalStr)) {
                            interval = Integer.parseInt(intervalStr);
                        }
                        if (interval == 1) {
                            MinaClientManager.getInstance().sendMessage(message + " TI1OK");
                            AppPreferencesUtils.putInt(context, PreferencesUtils.KEY_LOCATION_INTERVAL, interval);
                            RealTimeLocationManager.getInstance().updateLocationTime();
                        } else if (interval > 1) {
                            MinaClientManager.getInstance().sendMessage(message + " TIOK");
                            AppPreferencesUtils.putInt(context, PreferencesUtils.KEY_LOCATION_INTERVAL, interval);
                            RealTimeLocationManager.getInstance().updateLocationTime();
                        }
                    } else if (!TextUtils.isEmpty(message) && message.contains("tk=1")) {
                        // 立即进行一次上报
                        RealTimeLocationManager.getInstance().reportOnceLocation();
                    } else if (!TextUtils.isEmpty(message) && message.contains("cmd:uninstall")) {
                        //是否允许卸载"cmd:uninstall:true"
                        if (message.contains("true")) {
                            Log.i(TAG, "uninstall:true");
                            AppPreferencesUtils.putBoolean(context, PreferencesUtils.KEY_ALLOW_UNINSTALLATION, true);
                        } else {
                            Log.i(TAG, "uninstall:false");
                            AppPreferencesUtils.putBoolean(context, PreferencesUtils.KEY_ALLOW_UNINSTALLATION, false);
                        }
                        Log.i(TAG, "uninstall status:" + AppPreferencesUtils.getBoolean(context, PreferencesUtils.KEY_ALLOW_UNINSTALLATION, false));
                    } else if (!TextUtils.isEmpty(message) && message.contains("exitLogin")) {
                        if (BootApp.getInstance().isLogin()) {
                            Toast.makeText(context, "账号已在其他手机上登录，请重新登录,应用将在3秒后自动退出", Toast.LENGTH_LONG).show();
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    BootApp.getInstance().exitLogin();
                                    System.exit(0);
                                }
                            }, 3000L);
                        }
                    } */
                }
            }
        }
    }
}
